package cn.changeforyou.cmd.generator.db.mybatisplus;

import cn.changeforyou.analyzer.combine.orm.TableWriter;
import cn.changeforyou.analyzer.configFileParse.SpringBootConfigUtils;
import cn.changeforyou.analyzer.configFileParse.model.MysqlConfig;
import cn.changeforyou.analyzer.javaparse.JavaParseUtils;
import cn.changeforyou.analyzer.javaparse.model.EntityModel;
import cn.changeforyou.analyzer.naming.NamingStrategy;
import cn.changeforyou.cmd.generator.CmdGenerator;
import cn.changeforyou.cmd.generator.CmdGeneratorParameter;
import cn.changeforyou.cmd.generator.GeneratorContext;
import cn.changeforyou.cmd.generator.db.mybatisplus.parameters.Entity2TableGeneratorParamters;
import javax.validation.constraints.NotEmpty;

public class Entity2TableGenerator implements CmdGenerator {
	
	public static void main(String[] args) {
		Entity2TableGenerator generator = new Entity2TableGenerator();
		generator.start();
	}
	
	@Override
	public String getSign() {
		return "entity2TableGenerator";
	}
	
	@Override
	public boolean generate_do(GeneratorContext context, CmdGeneratorParameter params) {
		Entity2TableGeneratorParamters pa = (Entity2TableGeneratorParamters) params;
		@NotEmpty String entityName = pa.getEntityName();
		@NotEmpty String projectPath = pa.getProjectPath();
		MysqlConfig mysqlConfig = SpringBootConfigUtils.getMysqlConfigFromSpringBootProject(projectPath);
		if (null == mysqlConfig) {
			System.out.println("springboot 项目中配置db的文件没找到, 请先检查配置");
			return false;
		} else {
			System.out.println("解析到数据库配置: " + mysqlConfig);
		}
		
		//获取实体类信息
		EntityModel entityModel = JavaParseUtils.getJavaEntityModelFromEntityNameAndProjectPath(entityName, projectPath);
		if (log.isDebugEnabled()) {
			log.debug("实体类解析结果\n {}", entityModel);
		}
		if (null == entityModel) {
			throw new RuntimeException("实体类不存在");
		}
		TableWriter tableWriter = new TableWriter();
		tableWriter.setNamingStrategy(NamingStrategy.underline);
		String s = tableWriter.printCreateTableSql(entityModel);
		log.info("得到输出结果, 请复制\n{}", s);
		return true;
	}
	
	@Override
	public String getName() {
		return "根据mybatisPlus实体类自动创建表工具";
	}
	
	@Override
	public Class getParameterClass() {
		return Entity2TableGeneratorParamters.class;
	}
	
	@Override
	public void init(GeneratorContext context) {
	
	}
}
